package com.atguigu.dao;

import com.atguigu.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * base visit method
 * @author dl
 * @create 2020-04-18-10:51
 */
public class BaseDao<T> {
	/** 用来获取数据库连接 */
	private QueryRunner runner = new QueryRunner();
	/** 用来存放连接 进行事物控制 */
	private static Map<Thread,Connection> maps = new ConcurrentHashMap<>();

	public static Map<Thread, Connection> getMaps() {
		return maps;
	}

	public static void setMaps(Map<Thread, Connection> maps) {
		BaseDao.maps = maps;
	}

	private Class<T> type;

	public BaseDao() {
		// 获取父类的类型 并进行强转
		ParameterizedType superclass = (ParameterizedType) this.getClass().getGenericSuperclass();
		type = (Class<T>) superclass.getActualTypeArguments()[0];
	}

	/**
	 * 返回单条数据
	 * @return T
	 */
	public T getBean(String sql , Object ... params) {
		Connection conn = JDBCUtils.getConnection();
		T query = null;
		try {
			query = runner.query(conn, sql, new BeanHandler<>(type), params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return query;
	}

	/**
	 * 返回多条数据
	 * @return List<T>
	 */
	public List<T> getBeanList(String sql , Object ... params) {
		Connection conn = JDBCUtils.getConnection();
		List<T> query = null;
		try {
			query = runner.query(conn, sql, new BeanListHandler<>(type), params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return query;
	}

	/**
	 * 增删改操作
	 * @return int
	 */
	public int update(String sql , Object ... params) {
		Connection conn = JDBCUtils.getConnection();
		int update = 0;
		try {
			update = runner.update(conn, sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return update;
	}

	/**
	 * query total count
	 * @return int total count
	 */
	public Object queryTotalCount(String sql,Object ... param) {
		Connection conn = JDBCUtils.getConnection();
		Object query = null;
		try {
			query = runner.query(conn, sql, new ScalarHandler(),param);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return query;
	}

	/**
	 * 批量添加
	 * @param sql
	 * @param param
	 */
	public int[] batchSave(String sql , Object[] ... param) {
		Connection conn = JDBCUtils.getConnection();
		Object query = null;
		try {
//			conn.setAutoCommit(true);
			query = runner.batch(conn,sql, param);
		} catch (SQLException e) {
			System.out.println(e);
			throw new RuntimeException(e);
		}
		return (int[]) query;
	}



}
